#include "mypainter.h"
#include "ui_mypainter.h"

MyPainter::MyPainter(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MyPainter)
{
    ui->setupUi(this);

    this->setWindowTitle("Qt_绘图板");
    this->setWindowIcon(QIcon("tu.ico"));
    this->resize(1100,900);

    penColor = Qt::black;
    penWidth = 2;

    setMouseTracking(true);
    isPressed = false;

    //槽函数按钮响应：
    connect(ui->action_pen,SIGNAL(triggered()),this,SLOT(onColorDlgSlot()));
    connect(ui->action_width,SIGNAL(triggered()),this,SLOT(onWidthDlgSlot()));


}

MyPainter::~MyPainter()
{
    delete ui;
}

//绘图事件：
void MyPainter::paintEvent(QPaintEvent *ev)
{
    QPainter painter(this);


    for(int i = 0;i<lines.size();i++)
    {
        ColorLines* liness = lines[i];
        QPen pen;
        pen.setWidth(liness->width);
        pen.setColor(liness->color);
        painter.setPen(pen);
        painter.drawLine(liness->line->p1(),liness->line->p2());
        painter.save();

    }

}

//鼠标按下事件：
void MyPainter::mousePressEvent(QMouseEvent *ev)
{
    if(ev->button() == Qt::LeftButton)
        {
            isPressed = true;

            startPoint = ev->pos();
            endPoint = ev->pos();
        }
}

//鼠标移动事件：
void MyPainter::mouseMoveEvent(QMouseEvent *ev)
{
    if(isPressed == true)
    {
        endPoint = ev->pos();

        ColorLines* colorLine = new ColorLines;
        colorLine->line = new QLine(startPoint,endPoint);
        colorLine->color = penColor;
        colorLine->width = penWidth;


        lines.push_back(colorLine);

        //只要鼠标动就更新：
        update();

        startPoint = endPoint;
    }
}

//鼠标抬起事件：
void MyPainter::mouseReleaseEvent(QMouseEvent *ev)
{
    isPressed = false;
}

//弹出颜色选择对话框
void MyPainter::onColorDlgSlot()
{
    penColor = QColorDialog::getColor(Qt::black,this,"颜色选择对话框");

}

 //演出输入宽度
void MyPainter::onWidthDlgSlot()
{
    penWidth = QInputDialog::getInt(this,"请输入一个值","请输入画笔的宽度",0);
}

